//
//  SecondViewController.m
//  KeYin
//
//  Created by Sean Chen on 5/26/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CategoriesViewController.h"

@implementation CategoriesViewController

@synthesize magazines;
@synthesize magazineCell;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"科印期刊";
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(refresh)];
    self.navigationItem.rightBarButtonItem = item;
    [item release];
    
    //self.featuredPericals = [NSMutableArray array];
    
    [self loadWithPolicy:TTURLRequestCachePolicyDefault];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload
{
    [super viewDidUnload];

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc
{
    [super dealloc];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return magazines.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 128;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MagazineCell";
    
    MagazineCell *cell = (MagazineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"MagazineCell" owner:self options:nil];
        cell = magazineCell;
        self.magazineCell = nil;
    }
    
    // Configure the cell
    NSDictionary *dict = [magazines objectAtIndex:indexPath.row];
    
    cell.thumb.urlPath = [dict objectForKey:@"cover_img"];
    cell.title.text = [dict objectForKey:@"name"];
    cell.description.text = [dict objectForKey:@"description"];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - private

- (void)refresh {
    [self loadWithPolicy:TTURLRequestCachePolicyNetwork];
}

- (void)loadWithPolicy:(TTURLRequestCachePolicy)policy {
    NSString *URL = @"http://www.keyin.cn/ipad/magazines_list.php";
    TTURLRequest *request = [TTURLRequest requestWithURL:URL delegate:self];
    
    TTURLJSONResponse *response = [[TTURLJSONResponse alloc] init];
    request.response = response;
    [response release];
    
    request.cachePolicy = policy;
    
    [request send];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //FeaturedViewController *detailViewController = [[FeaturedViewController alloc] initWithNibName:@"FeaturedViewController" bundle:nil];
    
    NSDictionary *magazineDict = [magazines objectAtIndex:indexPath.row];
    FeaturedViewController *detailViewController = [[FeaturedViewController alloc] initWithMagazine:magazineDict];
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

#pragma mark - TTURLRequestDelegate

- (void)requestDidFinishLoad:(TTURLRequest*)request {
    TTURLJSONResponse *response = request.response;
    
    NSDictionary *rootDict = response.rootObject;
    NSDictionary *result = [rootDict objectForKey:@"result"];
    NSArray *entries = [result objectForKey:@"magazines"];
    
    self.magazines = entries;
    [self.tableView reloadData];
    
    //NSLog(@"featuredPericals = %@", entries);
}

- (void)request:(TTURLRequest*)request didFailLoadWithError:(NSError*)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"联网失败 请稍后再试" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

@end
